package game.engine;

import game.menu.MenuContainer;
import game.menu.MenuElement;
import game.menu.MenuElementWithOptions;
import game.utility.SettingsUtility;

import java.awt.event.KeyEvent;

public class OptionsMenuEngine extends AbstractMenuEngine {

	private static OptionsMenuEngine SINGLETON = new OptionsMenuEngine();

	public static OptionsMenuEngine newOptionsMenuEngine() {
		SINGLETON = new OptionsMenuEngine();
		return SINGLETON;
	}

	public static OptionsMenuEngine singleton() {
		return SINGLETON;
	}

	private MenuElementWithOptions selectedOptionMenu;

	private OptionsMenuEngine() {
		super();
	}

	@Override
	protected void actionForDown(MenuElement selectedElement) {
		if (selectedOptionMenu != null && selectedOptionMenu.isActive()) {
			selectedOptionMenu.cursorDown();
		} else {
			super.actionForDown(selectedElement);
		}
	}

	@Override
	protected void actionForEnter(MenuElement selectedElement) {
		if (selectedElement instanceof MenuElementWithOptions) {
			selectedOptionMenu = (MenuElementWithOptions) selectedElement;
		}
		if (selectedOptionMenu != null) {
			selectedOptionMenu.setActive(true);
		}
	}

	@Override
	protected void actionForUp(MenuElement selectedElement) {
		if (selectedOptionMenu != null && selectedOptionMenu.isActive()) {
			selectedOptionMenu.cursorUp();
		} else {
			super.actionForUp(selectedElement);
		}
	}

	@Override
	protected MenuContainer createContainer() {
		MenuContainer container = new MenuContainer(CONTAINER_XPOS, CONTAINER_YPOS);
		for (String key : SettingsUtility.singleton().getAllOptions().keySet()) {
			container.addMenuElementWithOptions(key);
		}
		return container;
	}

	@Override
	protected void navigationActions(KeyEvent e) {
		super.navigationActions(e);
		if (KeyEvent.VK_ESCAPE == e.getKeyCode()) {
			if (selectedOptionMenu != null) {
				selectedOptionMenu.setActive(false);
				selectedOptionMenu = null;
			} else {
				returnToPreviousEngine();
			}
		}
	}
}